package com.xxl.job.core.server;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.xxl.job.core.biz.ExecutorBiz;
import com.xxl.job.core.biz.impl.ExecutorBizImpl;
import com.xxl.job.core.biz.model.*;
import com.xxl.job.core.commons.constant.PluginConstant;
import com.xxl.job.core.commons.exception.DataxException;
import com.xxl.job.core.commons.response.ReturnCode;
import com.xxl.job.core.commons.vo.plugin.PluginQueryVo;
import com.xxl.job.core.thread.ExecutorRegistryThread;
import com.xxl.job.core.util.*;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.buffer.Unpooled;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.codec.http.*;
import io.netty.handler.timeout.IdleStateEvent;
import io.netty.handler.timeout.IdleStateHandler;
import io.netty.util.CharsetUtil;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import org.springframework.web.client.RestTemplate;

import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.HashMap;
import java.util.concurrent.*;

/**
 * Copy from : https://github.com/xuxueli/xxl-rpc
 *
 * @author xuxueli 2020-04-11 21:25
 */
@Component
public class EmbedServer {
    private static final Logger logger = LoggerFactory.getLogger(EmbedServer.class);

    private ExecutorBiz executorBiz;
    private Thread thread;

    public void start(final String address, final int port, final String appname, final String accessToken, final HashMap<String, Object> params) {
        executorBiz = new ExecutorBizImpl();
        thread = new Thread(new Runnable() {

            @Override
            public void run() {

                // param
                EventLoopGroup bossGroup = new NioEventLoopGroup();
                EventLoopGroup workerGroup = new NioEventLoopGroup();
                ThreadPoolExecutor bizThreadPool = new ThreadPoolExecutor(
                        0,
                        200,
                        60L,
                        TimeUnit.SECONDS,
                        new LinkedBlockingQueue<Runnable>(2000),
                        new ThreadFactory() {
                            @Override
                            public Thread newThread(Runnable r) {
                                return new Thread(r, "xxl-rpc, EmbedServer bizThreadPool-" + r.hashCode());
                            }
                        },
                        new RejectedExecutionHandler() {
                            @Override
                            public void rejectedExecution(Runnable r, ThreadPoolExecutor executor) {
                                throw new RuntimeException("xxl-job, EmbedServer bizThreadPool is EXHAUSTED!");
                            }
                        });


                try {
                    // start server
                    ServerBootstrap bootstrap = new ServerBootstrap();
                    bootstrap.group(bossGroup, workerGroup)
                            .channel(NioServerSocketChannel.class)
                            .childHandler(new ChannelInitializer<SocketChannel>() {
                                @Override
                                public void initChannel(SocketChannel channel) throws Exception {
                                    channel.pipeline()
                                            .addLast(new IdleStateHandler(0, 0, 30 * 3, TimeUnit.SECONDS))  // beat 3N, close if idle
                                            .addLast(new HttpServerCodec())
                                            .addLast(new HttpObjectAggregator(5 * 1024 * 1024))  // merge request & reponse to FULL
                                            .addLast(new EmbedHttpServerHandler(executorBiz, accessToken, bizThreadPool, params));
                                }
                            })
                            .childOption(ChannelOption.SO_KEEPALIVE, true);

                    // bind
                    ChannelFuture future = bootstrap.bind(port).sync();

                    logger.info(">>>>>>>>>>> xxl-job remoting server start success, nettype = {}, port = {}", EmbedServer.class, port);

                    // start registry
                    startRegistry(appname, address);

                    // wait util stop
                    future.channel().closeFuture().sync();

                } catch (InterruptedException e) {
                    if (e instanceof InterruptedException) {
                        logger.info(">>>>>>>>>>> xxl-job remoting server stop.");
                    } else {
                        logger.error(">>>>>>>>>>> xxl-job remoting server error.", e);
                    }
                } finally {
                    // stop
                    try {
                        workerGroup.shutdownGracefully();
                        bossGroup.shutdownGracefully();
                    } catch (Exception e) {
                        logger.error(e.getMessage(), e);
                    }
                }

            }

        });
        thread.setDaemon(true);    // daemon, service jvm, user thread leave >>> daemon leave >>> jvm leave
        thread.start();
    }

    public void stop() throws Exception {
        // destroy server thread
        if (thread != null && thread.isAlive()) {
            thread.interrupt();
        }

        // stop registry
        stopRegistry();
        logger.info(">>>>>>>>>>> xxl-job remoting server destroy success.");
    }


    // ---------------------- registry ----------------------

    /**
     * netty_http
     * <p>
     * Copy from : https://github.com/xuxueli/xxl-rpc
     *
     * @author xuxueli 2015-11-24 22:25:15
     */
    public static class EmbedHttpServerHandler extends SimpleChannelInboundHandler<FullHttpRequest> {
        private static final Logger logger = LoggerFactory.getLogger(EmbedHttpServerHandler.class);

        private ExecutorBiz executorBiz;
        private String accessToken;
        private ThreadPoolExecutor bizThreadPool;
        private String dataxPathPlugin;
        private String dataxPathBin;
        private String adminListPlugin;
        private String adminDownloadPlugin;

        public EmbedHttpServerHandler(ExecutorBiz executorBiz, String accessToken, ThreadPoolExecutor bizThreadPool, HashMap<String, Object> params) {
            this.executorBiz = executorBiz;
            this.accessToken = accessToken;
            this.bizThreadPool = bizThreadPool;
            if (params.containsKey("dataxPathPlugin") && null != params.get("dataxPathPlugin")) {
                this.dataxPathPlugin = params.get("dataxPathPlugin").toString();
            } else {
                logger.error("未配置datax plugin路径");
                throw new DataxException("未配置datax plugin路径");
            }
            if (params.containsKey("dataxPathBin") && null != params.get("dataxPathBin")) {
                this.dataxPathBin = params.get("dataxPathBin").toString();
            } else {
                logger.error("未配置datax bin路径");
                throw new DataxException("未配置datax bin路径");
            }
            if (params.containsKey("adminAddresses") && null != params.get("adminAddresses")) {
                this.adminDownloadPlugin = params.get("adminAddresses").toString() + "/plugin/download";
                this.adminListPlugin = params.get("adminAddresses").toString() + "/plugin/list";
            } else {
                logger.error("未配置调度中心地址");
                throw new DataxException("未配置调度中心地址");
            }
        }

        @Override
        protected void channelRead0(final ChannelHandlerContext ctx, FullHttpRequest msg) throws Exception {

            // request parse
            //final byte[] requestBytes = ByteBufUtil.getBytes(msg.content());    // byteBuf.toString(io.netty.util.CharsetUtil.UTF_8);
            String requestData = msg.content().toString(CharsetUtil.UTF_8);
            String uri = msg.uri();
            HttpMethod httpMethod = msg.method();
            boolean keepAlive = HttpUtil.isKeepAlive(msg);
            String accessTokenReq = msg.headers().get(XxlJobRemotingUtil.XXL_JOB_ACCESS_TOKEN);

            // invoke
            bizThreadPool.execute(new Runnable() {
                @Override
                public void run() {
                    // do invoke
                    Object responseObj = process(httpMethod, uri, requestData, accessTokenReq);

                    // to json
                    String responseJson = GsonTool.toJson(responseObj);

                    // write response
                    writeResponse(ctx, keepAlive, responseJson);
                }
            });
        }

        private Object process(HttpMethod httpMethod, String uri, String requestData, String accessTokenReq) {
            // valid
            if (HttpMethod.POST != httpMethod) {
                return new ReturnT<String>(ReturnT.FAIL_CODE, "invalid request, HttpMethod not support.");
            }
            if (uri == null || uri.trim().length() == 0) {
                return new ReturnT<String>(ReturnT.FAIL_CODE, "invalid request, uri-mapping empty.");
            }
            if (accessToken != null
                    && accessToken.trim().length() > 0
                    && !accessToken.equals(accessTokenReq)) {
                return new ReturnT<String>(ReturnT.FAIL_CODE, "The access token is wrong.");
            }

            // services mapping
            try {
                if ("/beat".equals(uri)) {
                    return executorBiz.beat();
                } else if ("/idleBeat".equals(uri)) {
                    IdleBeatParam idleBeatParam = GsonTool.fromJson(requestData, IdleBeatParam.class);
                    return executorBiz.idleBeat(idleBeatParam);
                } else if ("/run".equals(uri)) {
                    TriggerParam triggerParam = GsonTool.fromJson(requestData, TriggerParam.class);
                    return executorBiz.run(triggerParam);
                } else if ("/kill".equals(uri)) {
                    KillParam killParam = GsonTool.fromJson(requestData, KillParam.class);
                    return executorBiz.kill(killParam);
                } else if ("/log".equals(uri)) {
                    LogParam logParam = GsonTool.fromJson(requestData, LogParam.class);
                    return executorBiz.log(logParam);
                } else if ("/async".equals(uri)) {
                    RestTemplate restTemplate = new RestTemplate();
                    PluginQueryVo queryVo = new PluginQueryVo();
                    queryVo.setLimit(9999);
                    System.out.println("----开始同步插件-----");
                    System.out.println("--adminListPlugin:" + this.adminListPlugin);
                    System.out.println("--adminDownloadPlugin:" + this.adminDownloadPlugin);
                    System.out.println("--dataxPathBin:" + this.dataxPathBin);
                    System.out.println("--dataxPathPlugin:" + this.dataxPathPlugin);
                    com.xxl.job.core.commons.response.ReturnT<HashMap> returnT = new com.xxl.job.core.commons.response.ReturnT<>();
                    try {
                        returnT = restTemplate.getForObject(this.adminListPlugin, com.xxl.job.core.commons.response.ReturnT.class);
                    } catch (Exception e) {
                        return new ReturnT(ReturnCode.ERROR.getCode(), "执行器访问调度中心失败");
                    }

                    if (returnT.getCode().equals(com.xxl.job.core.commons.response.ReturnT.ok().getCode())) {
                        HashMap<String, Object> page = returnT.getData();
                        JSONArray list = JSONArray.parseArray(JSON.toJSONString(page.get("list")));
                        File readerFile = new File(dataxPathPlugin + "/" + PluginConstant.PLUGIN_TYPE_READER);
                        for (File file : readerFile.listFiles()) {
                            FileUtils.deleteDirectory(file);
                        }

                        File writerFile = new File(dataxPathPlugin + "/" + PluginConstant.PLUGIN_TYPE_WRITER);
                        for (File file : writerFile.listFiles()) {
                            FileUtils.deleteDirectory(file);
                        }
                        for (Object item : list) {
                            JSONObject jsonObject = JSONObject.parseObject(JSON.toJSONString(item));
                            String uuid = jsonObject.getString("uuid");
                            String fileName = jsonObject.getString("fileName");
                            String type = jsonObject.getString("type");
                            String downloadFilePath = downLoadFromUrl(this.adminDownloadPlugin + "?uuid=" + uuid, fileName, getFilePath(type));
                            unpackFile(new File(downloadFilePath), fileName, type);
                            System.out.println("完成同步插件：" + item);
                        }
                        System.out.println("同步数量：" + list.size());
                    }
                    System.out.println("----结束同步插件-----");
                    return com.xxl.job.core.commons.response.ReturnT.ok();
                } else {
                    return new ReturnT<String>(ReturnT.FAIL_CODE, "invalid request, uri-mapping(" + uri + ") not found.");
                }
            } catch (Exception e) {
                logger.error(e.getMessage(), e);
                return new ReturnT<String>(ReturnT.FAIL_CODE, "request error:" + ThrowableUtil.toString(e));
            }
        }

        /**
         * 从网络Url中下载文件
         *
         * @param urlStr
         * @param fileName
         * @param savePath
         * @throws IOException
         */
        public String downLoadFromUrl(String urlStr, String fileName, String savePath) throws IOException {
            URL url = new URL(urlStr);
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            //设置超时间为3秒
            conn.setConnectTimeout(3 * 1000);

            //得到输入流
            InputStream inputStream = conn.getInputStream();
            //获取自己数组
            byte[] getData = readInputStream(inputStream);

            //文件保存位置
            File saveDir = new File(savePath);
            if (!saveDir.exists()) {
                saveDir.mkdir();
            }
            File file = new File(saveDir + File.separator + fileName);
            FileOutputStream fos = new FileOutputStream(file);
            fos.write(getData);
            if (fos != null) {
                fos.close();
            }
            if (inputStream != null) {
                inputStream.close();
            }
            return saveDir + File.separator + fileName;


        }

        /**
         * 从输入流中获取字节数组
         *
         * @param inputStream
         * @return
         * @throws IOException
         */
        public static byte[] readInputStream(InputStream inputStream) throws IOException {
            byte[] buffer = new byte[1024];
            int len = 0;
            ByteArrayOutputStream bos = new ByteArrayOutputStream();
            while ((len = inputStream.read(buffer)) != -1) {
                bos.write(buffer, 0, len);
            }
            bos.close();
            return bos.toByteArray();
        }

        /**
         * 获取解析器存储路径
         */
        public String getFilePath(String type) {
            StringBuffer filePath = new StringBuffer();
            if (StringUtils.isNotEmpty(this.dataxPathPlugin)) {
                filePath.append(this.dataxPathPlugin);
            } else {
                filePath.append(Thread.currentThread().getContextClassLoader().getResource("datax/plugin").getPath());
            }
            //拼接解析器文件路径-判断根路径是否/结尾
            if (!this.dataxPathPlugin.endsWith(File.separator)) {
                filePath.append(File.separator);
            }
            //根据解析器类型存储到不同文件中（reader或writer）
            if (PluginConstant.PLUGIN_TYPE_READER.equals(type)) {
                filePath.append(PluginConstant.PLUGIN_TYPE_READER);
            } else if (PluginConstant.PLUGIN_TYPE_WRITER.equals(type)) {
                filePath.append(PluginConstant.PLUGIN_TYPE_WRITER);
            } else {
                DataxException.cast("解析器类型只能为reader或writer", ReturnCode.INVALID_PARAMETER);
            }
            filePath.append(File.separator);
            return filePath.toString();
        }

        /**
         * 更新文件，如果已存在，则替换
         */
        private void unpackFile(File file, String fileName, String type) {

            //获取解析器存储地址路径
            String filePath = getFilePath(type);
            //解析器存储地址根路径
            String fileParentPath = getFilePath(type);
            //解析器压缩文件路径
            filePath += fileName;
            //压缩后的文件
            String fileStorePath = filePath.replace(".zip", "");

            //如果压缩后的文件已存在
            File tmpFile = new File(fileStorePath);
            if (tmpFile.exists()) {
                DataxException.cast("解析器已存在", ReturnCode.FILE_OPERATION_ERROR);
            }

            //文件压缩
            try {
                ZipUtils.unPacket(filePath, fileStorePath);
            } catch (IOException e) {
                DataxException.cast("存储解析器文件时发生异常", ReturnCode.FILE_OPERATION_ERROR);
            }
            //删除压缩文件
            file.delete();
        }

        /**
         * write response
         */
        private void writeResponse(ChannelHandlerContext ctx, boolean keepAlive, String responseJson) {
            // write response
            FullHttpResponse response = new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.OK, Unpooled.copiedBuffer(responseJson, CharsetUtil.UTF_8));   //  Unpooled.wrappedBuffer(responseJson)
            response.headers().set(HttpHeaderNames.CONTENT_TYPE, "text/html;charset=UTF-8");       // HttpHeaderValues.TEXT_PLAIN.toString()
            response.headers().set(HttpHeaderNames.CONTENT_LENGTH, response.content().readableBytes());
            if (keepAlive) {
                response.headers().set(HttpHeaderNames.CONNECTION, HttpHeaderValues.KEEP_ALIVE);
            }
            ctx.writeAndFlush(response);
        }

        @Override
        public void channelReadComplete(ChannelHandlerContext ctx) throws Exception {
            ctx.flush();
        }

        @Override
        public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {
            logger.error(">>>>>>>>>>> xxl-job provider netty_http server caught exception", cause);
            ctx.close();
        }

        @Override
        public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception {
            if (evt instanceof IdleStateEvent) {
                ctx.channel().close();      // beat 3N, close if idle
                logger.debug(">>>>>>>>>>> xxl-job provider netty_http server close an idle channel.");
            } else {
                super.userEventTriggered(ctx, evt);
            }
        }
    }

    // ---------------------- registry ----------------------

    public void startRegistry(final String appname, final String address) {
        // start registry
        ExecutorRegistryThread.getInstance().start(appname, address);
    }

    public void stopRegistry() {
        // stop registry
        ExecutorRegistryThread.getInstance().toStop();
    }


}
